package io.zhengsh.juc._1aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

@Slf4j
public class SemaphoreTest {

    // 线程池
    private static final ExecutorService executorService = Executors.newFixedThreadPool(10);
    // 限制只有 5 个线程能够同时获取锁
    private static final Semaphore semaphore = new Semaphore(2);

    public static void main(String[] args) throws InterruptedException {
        // 场景，10 个线程，有序的获取共享锁
        for (int i = 0; i < 10; i++) {
            Thread.sleep(100);
            Runnable exec = SemaphoreTest::exec;

            executorService.submit(exec);
            executorService.submit(exec);
        }
    }

    // 执行逻辑
    public static void exec() {
        try {
            semaphore.acquire();
            log.info("执行 exec 方法");
            TimeUnit.SECONDS.sleep(2);
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }
    }
}
